package initialize

import (
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"week3zk-project/rpc/global"
	"week3zk-project/rpc/internal/model"
)

var once sync.Once

func InitMysql() {
	var err error
	app := &global.AppData.Server.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", app.Username, app.Password, app.Host, app.Port, app.Database)
	once.Do(func() {
		global.DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			panic(errors.New("数据库连接失败"))
			return
		}
		fmt.Println("数据库连接成功")
		global.DB.AutoMigrate(new(model.Goods))
	})
}
